package com.firefly.admin.common.config;

import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

import java.util.Collections;

@Configuration
public class CORSConfig {

    @Bean
    public FilterRegistrationBean filterRegistrationBean() {
        CorsConfiguration config = new CorsConfiguration();
        //允许所有域名进行跨域调用
        config.setAllowedOriginPatterns(Collections.singletonList("*"));//替换这个
        //2.允许任何请求头
        config.addAllowedHeader(CorsConfiguration.ALL);
        //3.允许任何方法
        config.addAllowedMethod(CorsConfiguration.ALL);
        //4.允许凭证
        config.setAllowCredentials(true);
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", config);
        CorsFilter corsFilter = new CorsFilter(source);
        FilterRegistrationBean<CorsFilter> filterRegistrationBean = new FilterRegistrationBean<>(corsFilter);
        filterRegistrationBean.setOrder(-101);
        return filterRegistrationBean;
    }
}
